<!--
  * 目录 表单 弹窗
  *
  * @Author:    dcsoft
  * @Date:      2022-08-21 19:52:43
  * @Wechat:    dctech
  * @Email:     dctech@dctech2020.com
  *@Copyright 山东东晨软件科技有限公司(https://www.dctech2020.com),since 2015
-->
<template>
  <a-modal
    :open="visible"
    :title="form.categoryId ? '编辑' : '添加'"
    ok-text="确认"
    cancel-text="取消"
    @ok="onSubmit"
    @cancel="onClose"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="{ span: 5 }"
      :wrapper-col="{ span: 12 }"
    >
      <a-form-item label="分类名称" name="categoryName">
        <a-input v-model:value="form.categoryName" placeholder="请输入分类名称" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import { message } from "ant-design-vue";
import _ from "lodash";
import { reactive, ref } from "vue";
import { categoryApi } from "/@/api/business/category/category-api";
import { SmartLoading } from "/@/components/framework/smart-loading";
import { smartSentry } from "/@/lib/smart-sentry";

// emit
const emit = defineEmits(["reloadList"]);

//  组件
const formRef = ref();

// ------------------------------ 显示 、隐藏 ------------------------------

// 是否展示抽屉
const visible = ref(false);

function showModal(categoryType, parentId, rowData) {
  Object.assign(form, formDefault);
  form.categoryType = categoryType;
  form.parentId = parentId;
  if (rowData && !_.isEmpty(rowData)) {
    Object.assign(form, rowData);
  }
  visible.value = true;
}

function onClose() {
  Object.assign(form, formDefault);
  visible.value = false;
}

// ------------------------------ 表单 ------------------------------

const formDefault = {
  categoryId: undefined,
  categoryName: "",
  categoryType: 1,
  parentId: undefined,
  disabledFlag: false,
};
let form = reactive({ ...formDefault });
const rules = {
  categoryName: [{ required: true, message: "请输入分类名称" }],
};

function onSubmit() {
  formRef.value
    .validate()
    .then(async () => {
      SmartLoading.show();
      try {
        if (form.categoryId) {
          await categoryApi.updateCategory(form);
        } else {
          await categoryApi.addCategory(form);
        }
        message.success(`${form.categoryId ? "修改" : "添加"}成功`);
        emit("reloadList", form.parentId);
        onClose();
      } catch (error) {
        smartSentry.captureError(error);
      } finally {
        SmartLoading.hide();
      }
    })
    .catch((error) => {
      console.log("error", error);
      message.error("参数验证错误，请仔细填写表单数据!");
    });
}

defineExpose({
  showModal,
});
</script>
